package com.qlm.tongji.service.impl;

import java.math.BigDecimal;
import java.util.Date;

import com.jfinal.plugin.activerecord.Db;
import com.qlm.tongji.entity.Summary;
import com.qlm.tongji.service.ISummaryService;

public class SummaryServiceImpl implements ISummaryService {

	@Override
	public Summary getSummary() {
		Summary summary = Summary.summaryDao
				.findFirst("select *  from summary order by id desc");
		return summary;
	}

	@Override
	public void addSummary() {
		BigDecimal yesterdayAmount;// 昨日红包发放总额
		BigDecimal totalAmount;// 累计红包发放总额

		Long yesterdayScanNum;// 昨日扫码总量
		Long totalUserNum;// 独立扫码用户总数

		Long totalScanNum;// 已扫二维码总数
		int totalQrcodeNum;// 二维码总数
		
		String sql="";
		
		sql = "SELECT sum(amount) totalAmount FROM (select DISTINCT qrcode_id,amount from hb_record)t";
		totalAmount = Db.use("tongji").findFirst(sql).getBigDecimal("totalAmount");

		sql = "SELECT sum(amount) yesterdayAmount FROM (select DISTINCT qrcode_id,amount from hb_record where TO_DAYS( NOW( ) ) - TO_DAYS( send_time) = 1)t;";
		yesterdayAmount = Db.use("tongji").findFirst(sql).getBigDecimal("yesterdayAmount");
		
		sql = "select count(DISTINCT qrcode_id) yesterdayScanNum from scan_record where TO_DAYS( NOW( ) ) - TO_DAYS( scan_time) = 1;";
		yesterdayScanNum = Db.use("tongji").findFirst(sql).getLong("yesterdayScanNum");
		
		sql = "SELECT count(distinct openid) totalUserNum FROM scan_record;";
		totalUserNum = Db.use("tongji").findFirst(sql).getLong("totalUserNum");
		
		sql = "select count(DISTINCT qrcode_id) totalScanNum from scan_record";
		totalScanNum = Db.use("tongji").findFirst(sql).getLong("totalScanNum");
		Summary summary = new Summary();
		Summary s = Summary.summaryDao.findFirst("select *  from summary order by id desc;");
		if(s ==null){
			totalQrcodeNum=0;
		}else{
			totalQrcodeNum=s.getInt("total_qrcode_num");
		}
		summary.set("yesterday_amount", yesterdayAmount);
		summary.set("total_amount", totalAmount);
		summary.set("yesterday_scan_num", yesterdayScanNum);
		summary.set("total_user_num", totalUserNum.intValue());
		summary.set("total_scan_num", totalScanNum.intValue());
		summary.set("total_qrcode_num", totalQrcodeNum);
		summary.set("create_time",new Date());
		summary.save();
	}

}
